package com.anysoft.utils.login;

import android.content.Context;

import com.anysoft.StaticField;
import com.anysoft.base.BaseActivity;
import com.anysoft.bean.PwdBean;
import com.anysoft.greenDAO.dao.PwdBeanDao;
import com.anysoft.greenDAO.db.DbCore;
import com.anysoft.other.SplashNewActivity;
import com.anysoft.utils.HttpUtils;
import com.anysoft.utils.MentorLogger;
import com.orhanobut.logger.Logger;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wwq on 2017/1/3.
 */

public class PwdBeanUtil {

    private static final String TAG = "PwdBeanUtil";

    public static PwdBeanDao mPwdBeanDao;

    private static PwdBeanUtil instance = null;

    private PwdBeanUtil() {
        mPwdBeanDao = DbCore.getDaoSession().getPwdBeanDao();
    }

    public static PwdBeanUtil getInstance() {
        if (instance == null) {
            instance = new PwdBeanUtil();
        }
        return instance;
    }

    /**
     * 保存/更新
     *
     * @param pwd               手势密码或指纹密码
     * @param type              0--指纹密码，1--手势密码
     * @param context
     * @param internetSecretKey 网络密钥
     * @param password          密码
     */
    public static void savePwd(String pwd, int type, Context context, String internetSecretKey, String password, String userId) {
        PwdBean pwdBean = mPwdBeanDao.queryBuilder().where(PwdBeanDao.Properties.UserId.eq(userId)).build().unique();
        boolean isNewBean = false;
        if (pwdBean == null) {
            pwdBean = new PwdBean();
            isNewBean = true;
        }
        MentorLogger.Log("userId----------pwd----------", userId);
        pwdBean.setUserId(userId);
        byte[] salt = PBKDF2_Utils.getSalt();
        String pwd_key = "";
        switch (type) {
            case 0:
//                pwdBean.setFingerprint_salt(salt);
//                pwd_key = PBKDF2_Utils.getRawKey(salt, pwd);
                break;
            case 1:
                pwdBean.setGesture_salt(salt);
                pwd_key = PBKDF2_Utils.getRawKey(salt, pwd);
                break;
            default:
                break;
        }


        BlowfishUtil blowfishUtil = new BlowfishUtil(BlowfishUtil.getMixKey(getLocalSecretKey(context, userId), pwd_key, internetSecretKey));
        //密文
        String ciphertext = blowfishUtil.encryptString(password);
        switch (type) {
            case 0:
                pwdBean.setFingerprint_ciphertext(ciphertext);
                break;
            case 1:
                pwdBean.setGesture_ciphertext(ciphertext);
                break;
            default:
                break;
        }

        if (isNewBean) {
            mPwdBeanDao.insert(pwdBean);//添加到数据库
            Logger.t(TAG).d("数据添加成功" + pwdBean.toString());
        } else {
            mPwdBeanDao.update(pwdBean);//更新数据库
            Logger.t(TAG).d("数据更新成功" + pwdBean.toString());
        }

        if (context instanceof BaseActivity) {
            switch (type) {
                case 0:
//                    ((BaseActivity) context).getEditor().putBoolean(MentorConst.IS_FINGER_PRINT_OPEN, true).commit();
                    Logger.t(TAG).d("MentorConst.IS_FINGER_PRINT_OPEN, true");
                    break;
                case 1:
//                    ((BaseActivity) context).getEditor().putBoolean(MentorConst.IS_GESTURE_PASSWORD_OPEN, true).commit();
                    Logger.t(TAG).d("MentorConst.IS_GESTURE_PASSWORD_OPEN, true");
                    break;
                default:
                    break;
            }
        }

    }

    /**
     * 查找
     *
     * @param userId
     * @param pwd
     * @param type              0--指纹密码，1--手势密码
     * @param context
     * @param internetSecretKey 网络密钥
     */
    public static String findDate(String userId, String pwd, int type, Context context, String internetSecretKey) {
        MentorLogger.Log(TAG, "userId---" + userId);
        PwdBean pwdBean = mPwdBeanDao.queryBuilder().where(PwdBeanDao.Properties.UserId.eq(userId)).build().unique();

//        PwdBean pwdBean = mPwdBeanDao.queryBuilder()
//                .where(PwdBeanDao.Properties.Id.notEq(-1))
//                .orderAsc(PwdBeanDao.Properties.Id)
//                .limit(5)
//                .build().list().get(0);
        Logger.t("list-----").d(mPwdBeanDao.queryBuilder()
                .where(PwdBeanDao.Properties.Id.notEq(-1))
                .orderAsc(PwdBeanDao.Properties.Id)
                .limit(5)
                .build().list());
        String pwd_key = "";
        switch (type) {
            case 0:
//                    pwd_key = PBKDF2_Utils.getRawKey(userList.get(i).getFingerprint_salt(), pwd);
                break;
            case 1:
                pwd_key = PBKDF2_Utils.getRawKey(pwdBean.getGesture_salt(), pwd);
                break;
            default:
                break;
        }


        BlowfishUtil blowfishUtil = new BlowfishUtil(BlowfishUtil.getMixKey(getLocalSecretKey(context, userId),
                pwd_key, internetSecretKey));

        String password = "";

        switch (type) {
            case 0:
                MentorLogger.Log(TAG, pwdBean);
                password = blowfishUtil.decryptString(pwdBean.getFingerprint_ciphertext().toString());
                //System.out.println("解密后信息：" + password);
                break;
            case 1:
                password = blowfishUtil.decryptString(pwdBean.getGesture_ciphertext().toString());
                //System.out.println("解密后信息：" + password);
                break;
        }

        return password;
    }

    public static String findUserId() {
        List<PwdBean> list = new ArrayList<>();
        try {
            list.addAll(mPwdBeanDao.queryBuilder()
                    .where(PwdBeanDao.Properties.Id.notEq(-1))
                    .orderAsc(PwdBeanDao.Properties.Id)
//                .limit(5)
                    .build().list());
        } catch (Exception e) {
            Logger.t(TAG).d(e);
        }

        if (list != null && !list.isEmpty() && list.size() > 0) {
            return list.get(0).getUserId();
        } else {
            return "";
        }

    }


    /**
     * 删除
     *
     * @param userId
     * @param userType
     */
    public static void deleteDate(String userId, String userType) {
        QueryBuilder qb = mPwdBeanDao.queryBuilder();
        PwdBean pwdBean = (PwdBean) qb.where(qb.and(PwdBeanDao.Properties.UserId.eq(userId), PwdBeanDao.Properties.UserType.eq(userType)))
                .build().unique();

//        PwdBean pwdBean = mPwdBeanDao.queryBuilder().where(PwdBeanDao.Properties.UserId.eq(userId)).build().unique();
        if (pwdBean != null) {
            mPwdBeanDao.deleteByKey(pwdBean.getId());
            Logger.t(TAG).d("删除成功");
        } else {
            Logger.t(TAG).d("用户不存在,id为" + userId);
        }
    }

    /**
     * 删除秘钥
     *
     * @param userId
     * @param type   0--指纹密码，1--手势密码
     */
    public static void deletePwd(Context context, String userId, int type) {
        PwdBean pwdBean = mPwdBeanDao.queryBuilder().where(PwdBeanDao.Properties.UserId.eq(userId)).build().unique();
        if (pwdBean != null) {
            switch (type) {
                case 0:
                    pwdBean.setFingerprint_ciphertext("");
                    break;
                case 1:
                    pwdBean.setGesture_ciphertext("");
                    pwdBean.setGesture_salt(null);
                    break;
                default:
                    break;
            }
            mPwdBeanDao.update(pwdBean);
            if (context instanceof BaseActivity) {
                switch (type) {
                    case 0:
//                        ((BaseActivity) context).getEditor().putBoolean(MentorConst.IS_FINGER_PRINT_OPEN, false).commit();
                        Logger.t(TAG).d("指纹密码删除成功");
                        break;
                    case 1:
//                        ((BaseActivity) context).getEditor().putBoolean(MentorConst.IS_GESTURE_PASSWORD_OPEN, false).commit();
                        Logger.t(TAG).d("手势密码删除成功");
                        break;
                    default:
                        break;
                }

            }
        } else {
            Logger.t(TAG).d("用户不存在,id为" + userId);
        }
    }

    /**
     * 删除全部
     */
    public static void clearDate(Context context) {
        mPwdBeanDao.deleteAll();
    }

    /**
     * 更新
     *
     * @param newPwdBean
     */
    public static void updateDate(PwdBean newPwdBean) {
        PwdBean pwdBean = mPwdBeanDao.queryBuilder().where(PwdBeanDao.Properties.UserId.eq(newPwdBean.getUserId())).build().unique();
        if (pwdBean != null) {
            pwdBean = newPwdBean;
            mPwdBeanDao.update(pwdBean);
            Logger.t(TAG).d("修改成功");
        } else {
            Logger.t(TAG).d("用户不存在,id为" + newPwdBean.getUserId());
        }
    }

    public static String getLocalSecretKey(Context context, String userId) {
        //TODO 用户id要获取
        return HttpUtils.getMD5(userId + SplashNewActivity.UUID + StaticField.getVersionName(context) + StaticField
                .getPackageName(context));
    }

    public static boolean isTheSameUser(String userId) {
        PwdBean pwdBean = mPwdBeanDao.queryBuilder().where(PwdBeanDao.Properties.UserId.eq(userId)).build().unique();
        //TODO 用户id要获取
        return pwdBean != null;
    }
}
